package com.norns.torque.dialog

import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.activityViewModels
import com.hi.dhl.binding.viewbind
import com.norns.torque.WifiDeviceViewModel
import com.norns.torque.databinding.DialogAddDeviceBinding
import com.norns.torque.entrty.WifiDevice
import com.norns.torque.utils.AppContext
import java.util.regex.Matcher
import java.util.regex.Pattern


class AddDeviceDialog: CommonDialog(){
    private val viewModel: WifiDeviceViewModel by activityViewModels()
    companion object{
        fun newInstance():AddDeviceDialog {
            val args = Bundle()
            val fragment = AddDeviceDialog()
            fragment.arguments = args
            return fragment
        }
    }
    private val ipAddressPattern: String =
        "^((([1-9]?\\d|1\\d{2}|2[0-4]\\d|25[0-5])\\.){3})([1-9]?\\d|1\\d{2}|2[0-4]\\d|25[0-5])$"

    fun isValidIPAddress(ipAddress: String): Boolean {
        val pattern: Pattern = Pattern.compile(ipAddressPattern)
        val matcher: Matcher = pattern.matcher(ipAddress)
        return matcher.matches()
    }


    private val binding by viewbind<DialogAddDeviceBinding>()
    private var btnClickListener:((wifi:String,pwd:String)->Unit)?=null

    fun setClickListener(listener:(wifi:String,pwd:String)->Unit){
        btnClickListener=listener
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        screenWidthAspect=0.9f
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.btnConfirm.setOnClickListener {
            var deviceName=binding.editName.text.toString()
            val deviceAddress=binding.editAddress.text.toString()
            val devicePort=binding.editPort.text.toString()
            if (deviceAddress.isEmpty()){
                showToast("设备IP地址不能为空")
                return@setOnClickListener
            }
            val isAddresses=isValidIPAddress(deviceAddress)
            if (!isAddresses){
                showToast("IP地址不合法，请重新输入")
                return@setOnClickListener
            }
            if (devicePort.isEmpty()){
                showToast("设备端口号不能为空")
                return@setOnClickListener
            }
            if (deviceName.isEmpty()){
                val subStrs= deviceAddress.split(".")
                var lastStr=""
                if (subStrs.size>2){
                    lastStr+=subStrs[subStrs.lastIndex-1]
                    lastStr+=subStrs[subStrs.lastIndex]
                }
                deviceName="ESP32:${lastStr}"
            }
            val wifiDevice= WifiDevice(deviceName,deviceAddress,devicePort.toInt())
            viewModel.saveDevice(wifiDevice)
            dismiss()
        }
        binding.btnCancel.setOnClickListener {
            dismiss()
        }
    }
    private fun showToast(msg: String) {
        val toast = Toast.makeText(AppContext.context, msg, Toast.LENGTH_SHORT)
        toast.setGravity(Gravity.TOP, 0, 400)
        toast.show()
    }
}